import type { App } from "vue";

import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
  isNavigationFailure,
  NavigationFailureType,
} from "vue-router";
import { routes } from "./route";
import NProgress from "@/utils/nprogress";
import { useLayoutStore } from "@/store/modules/layout-store";

/**
 * 创建路由器实例
 */
const router = createRouter({
  // history: createWebHashHistory(), // 路由哈希模式（url带#）
  history: createWebHistory(), // 浏览器html5模式（url不带#）
  routes: routes,
  // 刷新时，滚动条位置还原
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// 解决重复导航问题
const originalPush = router.push;
router.push = function push(location) {
  return originalPush.call(this, location).catch((err) => {
    // 如果是导航取消错误，则不抛出错误
    if (isNavigationFailure(err, NavigationFailureType.cancelled)) {
      console.warn("Navigation cancelled:", err);
      return err;
    }
    // 其他错误正常抛出
    throw err;
  });
};
// 路由守卫
const whiteList = ["/login"];
router.beforeEach((to, from, next) => {
  NProgress.start();

  try {
    // 路由白名单配置
    if (whiteList.includes(to.path)) {
      next();
    } else {
      // 未登录处理
      // next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
      NProgress.done();
    }

    // 已登录登录页重定向
    if (to.path === "/login") {
      next({ path: "/" });
      return;
    }

    // 动态标题设置
    const title = (to.params.title as string) || (to.query.title as string);
    if (title) {
      to.meta.title = title;
    }
    next();
  } catch (error) {
    // 错误处理：重置状态并跳转登录
    console.error("Route guard error:", error);
    next("/login");
    NProgress.done();
  }
});
router.afterEach((to, from, failure) => {
  if (isNavigationFailure(failure)) {
    console.log("failed navigation", failure);
    // 如果是导航取消，不执行 NProgress.done()
    if (!isNavigationFailure(failure, NavigationFailureType.cancelled)) {
      NProgress.done();
    }
    return;
  }
  useLayoutStore().toggleTopMenus({ path: to.path });
  NProgress.done();
});
// 路由跳转异常捕获
router.onError((error) => {
  console.error("Router error:", error);
});

// 全局注册 router
export function setupRouter(app: App<Element>) {
  app.use(router);
}

export default router;
